package com.atguigu;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName CASDemo
 * @Author yy
 * @create 2022/9/8 18:44
 */

/*
 * 多线程环境 不使用    原子类AtomicInteger保证线程安全（基本数据类型）
 *
 *多线程环境   使用    原子类AtomicInteger保证线程安全（基本数据类型）
 */

public class CASDemo {

    private volatile int number = 0;

    public int getNumber() {
        return number;
    }

    public synchronized void setNumber() {
        number++;
    }

    //=============JUC CAS
    private AtomicInteger atomicInteger = new AtomicInteger();//默认为0

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
        atomicInteger.getAndIncrement();
    }

    public static void main(String[] args) throws InterruptedException {
        CASDemo casDemo = new CASDemo();
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 1; i <= 100; i++) {
            new Thread(()->{
                for (int j = 0; j < 100; j++) {
                    casDemo.setNumber();
                    casDemo.setAtomicInteger();
                }
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }
        countDownLatch.await();

        System.out.println(Thread.currentThread().getName()+"\t"+"最后结果："+casDemo.getNumber());
        System.out.println(Thread.currentThread().getName()+"\t"+"最后结果："+casDemo.getAtomicInteger());

        helloCAS();
    }

    private static void helloCAS(){
        AtomicInteger atomicInteger = new AtomicInteger(5);
        System.out.println(atomicInteger.compareAndSet(5, 6)+"\t"+atomicInteger.getAndIncrement());
        System.out.println(atomicInteger.compareAndSet(7, 15)+"\t"+atomicInteger.get());
    }

//
//    private static void helloCAS() {
//        AtomicInteger atomicInteger = new AtomicInteger(5);
//        System.out.println(atomicInteger.addAndGet(6));
//        System.out.println(atomicInteger.get());
//
//        System.out.println(atomicInteger.compareAndSet(11, 7) +"\t"+ atomicInteger.getAndIncrement());
//
//        System.out.println(atomicInteger.compareAndSet(8, 20) + "\t" + atomicInteger.get());
//    }
}
